package com.hh.jedis;

import redis.clients.jedis.Jedis;

import java.util.Random;
import java.util.Scanner;

public class JedisDemo {
    public static void main(String[] args) {
        JedisDemo jd=new JedisDemo();
        String phone="14578774132";
        String code=jd.js(phone);
        if(code.equals("top") || code.equals("else")){
            System.out.println("验证码发送次数已达上限");
        }
        else{
            System.out.println(code);
            Scanner scanner=new Scanner(System.in);
            System.out.println("输入验证码：");
            String s=scanner.next();
            jd.yesOrNo(phone,s);
        }

    }
    //生成6为验证码
    public String get6Code(){
        Random random=new Random();
        String s="";
        for(int i=1;i<=6;i++){
            int r=random.nextInt(10);
            s=s+r;
        }
        return s;
    }
    //验证码两分钟有效
    public String second2(String phone){
        Jedis jedis=new Jedis("192.168.145.128",6379);
        String key="yz"+phone;
        String code=get6Code();
        jedis.setex(key,60*2,code);
        return code;

    }
    //验证验证码是否正确
    public void yesOrNo(String phone,String code){

        Jedis jedis=new Jedis("192.168.145.128",6379);
        String yz=jedis.get("yz"+phone);
        if(yz.equals(code)){
            System.out.println("验证成功");
        }
        else{
            System.out.println("验证失败");
        }
    }
    //每个手机每天只能发送三次验证码
    public String js(String phone){
        Jedis jedis=new Jedis("192.168.145.128",6379);
        String key ="cs"+phone;
        if(jedis.get(key)==null || jedis.get(key)==""){
            jedis.setex(key,60*60*24,"1");
            String code=second2(phone);
            return code;
        }
        else if(Integer.valueOf(jedis.get(key))<=3){
            jedis.incr(key);
            String code=second2(phone);
            return code;
        }
        else if(Integer.valueOf(jedis.get(key))>3){
            return "top";
        }
        return "else";
    }

}
